<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Attachment;
use app\common\model\Version;
use fast\Random;
use OSS\Core\OssException;
use OSS\OssClient;
use think\captcha\Captcha;
use think\Config;
use think\Hook;
use think\Model;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @param $id
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    public function init_config(){
        $data['logo']=config('site.logo')?cdnurl(config('site.logo'),true):'';
        $data['privacy']=\config('site.privacy');
        $data['mini_logo']=config('site.logo')?cdnurl(config('site.logo'),true):'';
        $data['contact_phone']=config('site.contact_phone');
        $this->success('',$data);
    }
    /**
     * @title 上传文件(上传到oss)
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function ossupload(){
        $file = $this->request->file('file');
        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }
        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $config = get_addon_config('alioss');
        $filename=md5(mt_rand());
        $name=$filename.".".$suffix;
        $md5 = md5_file($fileInfo['tmp_name']);

        $auth = new \addons\alioss\library\Auth();
        $temp_params =$params = $auth->params($name, $md5, false);
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        $accessKeyId = $config['accessKeyId'];
        $accessKeySecret = $config['accessKeySecret'];
        // Endpoint以杭州为例，其它Region请按实际情况填写。"http://oss-cn-hangzhou.aliyuncs.com"
        $endpoint = $config['endpoint'];
        // 存储空间名称
        $bucket= $config['bucket'];

        $sha1=sha1_file($fileInfo['tmp_name']);
        $imagewidth = $imageheight = 0;
        $imgInfo = getimagesize($fileInfo['tmp_name']);
        $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
        $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;

        $fileName=$params['key'];
        $url = '/' . $fileName;

        // 判断如果是图片
        if($imgInfo){
            $arr=explode('/', $url);
            $temp_url=ROOT_PATH . '/public/uploads/' .rand(1,200).end($arr); //拼接上随机数，防止有用户同时上传一样的图片
            // 压缩图片
            $imgcompress=new \app\common\library\Imgcompress($fileInfo['tmp_name']);
            $imgcompress->getimg($temp_url);
            // 检测图片是否违规
            $wxmini=new \app\common\library\Wxmini();
            $check_result=$wxmini->checkMedia($temp_url);
            unlink($temp_url);//删除图片
            if($check_result['errcode']!=0){
                $this->error($check_result['errmsg']);
            }
        }
        $extparam = $this->request->post();
        $saveparams = array(
            'admin_id'    => session('admin.id'),
            'user_id'     => $this->auth->id,
            'filesize'    => $fileInfo['size'],
            'filename'    => $fileInfo['name'],
            'imagewidth'  => $imagewidth,
            'imageheight' => $imageheight,
            'imagetype'   => $suffix,
            'imageframes' => 0,
            'mimetype'    => $fileInfo['type'],
            'url'         => $url,
            'uploadtime'  => time(),
            'storage'     => 'alioss',
            'sha1'        => $sha1,
            'extparam'    => json_encode($extparam),
        );
        $attachment = new Attachment();
        $attachment->data(array_filter($saveparams));
        $attachment->save();
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            //执行阿里云上传
            $result = $ossClient->uploadFile($config['bucket'], $fileName, $fileInfo['tmp_name']);

            $this->success("上传成功", ['url'=>$url,'fullurl'=>cdnurl($url,true)]);
        } catch(OssException $e) {
            $this->error('无法上传到远程服务器，错误:' . $e->getMessage());
            exit;
        }
    }
}
